<template>
    <div style="height: 100%;width: 100%;">
        <el-row
            style="background-image: url('../../static/img/标题框.png');background-repeat: repeat-x;background-size: 100% 150px;">
            <el-col :span="7">
                <div class="navsp">{{ BTCtime }}(BTC)&nbsp;&nbsp;&nbsp;&nbsp;{{ UTCtime }}(UTC)</div>
            </el-col>
            <el-col :span="10">
                <div class="tit" style="position: relative;">
                    检前数据同步业务监控中心
                </div>
            </el-col>
            <el-col :span="7" style="line-height: 45px;font-size: 20px;text-align: center;">
                <el-button class="btn" type="primary" @click="handleOperation('restart_pro')" :loading="restartLoading">重启进程</el-button>
                <el-button class="btn" type="primary" @click="handleOperation('modify_path')">修改路径</el-button>
                <el-button class="btn" type="primary" @click="handleOperation('data_retransmission')">数据重传</el-button>
                <el-button v-if="isLoggedIn" type="danger" size="small" @click="logout">退出登录</el-button>
            </el-col>
        </el-row>
        <!-- 路径配置弹窗 -->
        <path-config-dialog :visible.sync="pathConfigVisible" />
        
        <!-- 数据重传列表弹窗 -->
        <el-dialog
            title="数据重传列表"
            :visible.sync="fileManagerVisible"
            width="80%"
            :before-close="closeFileManagerDialog"
            class="file-manager-dialog"
        >
            <div class="file-manager-container">
                <!-- 站点选择 -->
                <div class="station-selector">
                    <el-radio-group v-model="selectedStation" @change="handleStationChange">
                        <el-radio-button label="MY">密云站</el-radio-button>
                        <el-radio-button label="WQ">武清站</el-radio-button>
                    </el-radio-group>
                </div>
                
                <!-- 文件路径导航 -->
                <div class="path-navigator">
                    <el-breadcrumb separator="/">
                        <el-breadcrumb-item v-for="(item, index) in breadcrumbItems" :key="index">
                            <span v-if="index === breadcrumbItems.length - 1">{{ item.name }}</span>
                            <a v-else @click="navigateToBreadcrumb(index)">{{ item.name }}</a>
                        </el-breadcrumb-item>
                    </el-breadcrumb>
                </div>
                
                <!-- 文件列表 -->
                <div class="file-list-container" v-loading="fileListLoading">
                    <el-table
                        ref="fileTable"
                        :data="paginatedFileList"
                        style="width: 100%"
                        @row-click="handleRowClick"
                        @selection-change="handleSelectionChange"
                    >
                        <el-table-column
                            type="selection"
                            width="55"
                        ></el-table-column>
                        <el-table-column
                            prop="name"
                            label="文件名"
                        >
                            <template slot-scope="scope">
                                <i class="el-icon-folder" v-if="scope.row.isDirectory"></i>
                                <i class="el-icon-document" v-else></i>
                                <span style="margin-left: 5px">{{ scope.row.name }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="type"
                            label="类型"
                            width="100"
                        >
                            <template slot-scope="scope">
                                {{ scope.row.isDirectory ? '文件夹' : '文件' }}
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="fileCount"
                            label="文件数量"
                            width="100"
                            align="center"
                        >
                            <template slot-scope="scope">
                                <span v-if="scope.row.isDirectory">
                                    <template v-if="scope.row.fileCount === undefined">加载中...</template>
                                    <template v-else-if="scope.row.fileCount === 0">暂无</template>
                                    <template v-else>{{ scope.row.fileCount }}</template>
                                </span>
                                <span v-else>-</span>
                            </template>
                        </el-table-column>
                    </el-table>
                    <!-- 分页控件 -->
                    <div style="margin: 20px 0; text-align: right;">
                        <el-pagination
                            background
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="fileList.length"
                            :page-size="pageSize"
                            :current-page="currentPage"
                            :page-sizes="pageSizes"
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                        />
                    </div>
                </div>
                
                <!-- 选中文件列表 -->
                <div class="selected-files-container" v-if="selectedFiles.length > 0">
                    <div class="selected-files-header">
                        <span class="selected-title">已选择 {{ selectedFiles.length }} 个文件</span>
                        <el-button type="text" @click="clearSelectedFiles">清空</el-button>
                    </div>
                    <div class="selected-files-tags">
                        <el-tag
                            v-for="file in selectedFiles"
                            :key="file.path"
                            closable
                            @close="removeSelectedFile(file)"
                            class="file-tag"
                        >
                            {{ file.name }}
                        </el-tag>
                    </div>
                </div>
            </div>
            
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeFileManagerDialog">取消</el-button>
                <el-button type="primary" @click="submitRetransmission" :loading="retransmissionLoading" :disabled="selectedFiles.length === 0">
                    确认重传
                </el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import moment from 'moment'
import config from "@/utils/config";
const { DMSip } = config;
import PathConfigDialog from '@/views/PreTestData.vue'
import { isLoggedIn, checkPermission, removeToken } from "../utils/auth";

export default {
    components: {
        PathConfigDialog
    },
    data() {
        return {
            UTCtime: '',
            BTCtime: '',
            // 定时器
            timer: '',
            // 按钮加载状态
            restartLoading: false,
            // 路径配置弹窗显示状态
            pathConfigVisible: false,
            // 数据重传列表弹窗
            fileManagerVisible: false,
            // 文件列表加载状态
            fileListLoading: false,
            // 数据重传加载状态
            retransmissionLoading: false,
            // 选择的站点
            selectedStation: 'MY',
            // 当前路径
            currentPath: '',
            // 面包屑导航数据
            breadcrumbItems: [],
            // 文件列表
            fileList: [],
            // 选中的文件
            selectedFiles: [],
            // 根目录映射
            rootPaths: {
                'MY': '/PREDATA-MY',
                'WQ': '/PREDATA-WQ'
            },
            isNavigating: false, // 新增：目录切换锁
            // 分页相关
            currentPage: 1,         // 当前页码
            pageSize: 20,           // 每页条数
            pageSizes: [10, 20, 50, 100], // 可选每页条数
        }
    },
    computed: {
        isLoggedIn() {
            return isLoggedIn();
        },
        // 分页后的文件列表
        paginatedFileList() {
            const start = (this.currentPage - 1) * this.pageSize;
            const end = start + this.pageSize;
            return this.fileList.slice(start, end);
        }
    },
    created() {
        this.start()
    },
    methods: {
        // 处理需要权限的操作
        handleOperation(operationName) {
            // 检查是否需要登录验证
            if (!checkPermission(operationName)) {
                // 未登录，显示确认提示框
                this.$confirm('该操作需要登录权限，是否跳转到登录页面？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // 用户确认，跳转到登录页面
                    this.$router.push({
                        path: '/login',
                        query: { redirect: this.$route.fullPath }
                    });
                }).catch(() => {
                    // 用户取消，不做任何操作
                    this.$message.info('已取消操作');
                });
                return;
            }
            
            // 已登录，根据操作类型执行相应操作
            switch (operationName) {
                case 'restart_pro':
                    this.restart_pro();
                    break;
                case 'modify_path':
                    this.showPathConfig();
                    break;
                case 'data_retransmission':
                    this.showFileManagerDialog();
                    break;
                default:
                    break;
            }
        },
        
        // 退出登录
        logout() {
            this.$confirm('确定要退出登录吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                removeToken();
                this.$message.success('已退出登录');
                // 刷新页面以更新状态
                this.$router.go(0);
            }).catch(() => {
                this.$message.info('已取消退出');
            });
        },
        
        // 显示路径配置弹窗
        showPathConfig() {
            this.pathConfigVisible = true
        },
        //重启进程
        restart_pro() {
            this.$confirm('确定要重启进程吗？重启后所有同步任务将重新开始', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                center: true
            }).then(() => {
                this.restartLoading = true
                this.$axios({
                    method: "post",
                    url: DMSip + '/-/bin.preData.restart_pro',
                }).then((res) => {
                    if (res.data && res.data.code === 200) {
                        this.$message({
                            type: 'success',
                            message: '进程重启成功',
                            duration: 3000
                        })
                        // 重启成功后刷新页面数据
                        this.$emit('restart-success')
                    } else {
                        this.$message({
                            type: 'error',
                            message: res.data.msg || '进程重启失败',
                            duration: 3000
                        })
                    }
                }).catch(error => {
                    console.error('重启进程失败:', error)
                    this.$message({
                        type: 'error',
                        message: '重启进程失败，请检查网络连接',
                        duration: 3000
                    })
                }).finally(() => {
                    this.restartLoading = false
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消重启',
                    duration: 2000
                })
            })
        },
        // 日期
        valChange() {
            this.BTCtime = moment(new Date().getTime()).format('YYYY-MM-DD HH:mm:ss');
            this.UTCtime = moment(new Date().getTime()).utc().format('YYYY-MM-DD HH:mm:ss');
        },
        // 定时器
        start() {
            this.timer = setInterval(this.valChange, 1000)
        },
        // 显示数据重传列表弹窗
        showFileManagerDialog() {
            this.fileManagerVisible = true
            this.selectedStation = 'MY'
            this.currentPath = this.rootPaths.MY
            this.breadcrumbItems = [
                { name: '根目录', path: this.rootPaths.MY }
            ]
            this.selectedFiles = []
            this.fetchFileList()
        },
        
        // 关闭数据重传列表弹窗
        closeFileManagerDialog() {
            this.fileManagerVisible = false
            this.fileList = []
            this.selectedFiles = []
        },
        
        // 获取文件列表
        fetchFileList(clickedRow = null) {
            this.fileListLoading = true;
            this.$axios({
                method: "post",
                url: DMSip + '/-/bin.preData.get_path',
                data: JSON.stringify({
                    path: this.currentPath
                }),
            }).then(res => {
                if (res.data && res.data.code === 200 && Array.isArray(res.data.data)) {
                    this.fileList = res.data.data.map(item => {
                        const isDirectory = !item.includes('.');
                        const fileInfo = {
                            name: item,
                            path: `${this.currentPath}/${item}`,
                            isDirectory: isDirectory,
                            selected: false
                        };
                        if (isDirectory) {
                            this.fetchDirectoryFileCount(fileInfo);
                        }
                        return fileInfo;
                    });
                    // 只有接口返回成功后再push面包屑
                    if (clickedRow) {
                        this.breadcrumbItems.push({
                            name: clickedRow.name,
                            path: clickedRow.path
                        });
                    }
                    // 文件列表变化时重置分页
                    this.currentPage = 1;
                } else {
                    this.$message.error('获取文件列表失败');
                }
            }).catch(error => {
                console.error('获取文件列表失败:', error);
                this.$message.error('获取文件列表失败，请检查网络连接');
            }).finally(() => {
                this.fileListLoading = false;
                this.isNavigating = false; // 解锁
            });
        },
        
        // 获取目录中的文件数量
        fetchDirectoryFileCount(fileInfo) {
            this.$axios({
                method: "post",
                url: DMSip + '/-/bin.preData.get_path',
                data: JSON.stringify({
                    path: fileInfo.path
                }),
            }).then(res => {
                if (res.data && res.data.code === 200 && Array.isArray(res.data.data)) {
                    // 更新文件数量，如果目录为空则设置为0
                    this.$set(fileInfo, 'fileCount', res.data.data.length || 0);
                }
            }).catch(error => {
                console.error('获取目录文件数量失败:', error);
                this.$set(fileInfo, 'fileCount', '获取失败');
            });
        },
        
        // 处理站点变更
        handleStationChange(value) {
            this.currentPath = this.rootPaths[value]
            this.breadcrumbItems = [
                { name: '根目录', path: this.currentPath }
            ]
            this.selectedFiles = []
            this.fetchFileList()
        },
        
        // 处理行点击事件
        handleRowClick(row) {
            if (this.isNavigating) return; // 正在加载时禁止点击
            if (row.isDirectory) {
                this.isNavigating = true; // 加锁
                this.currentPath = row.path;
                // 不要立即push面包屑，等接口返回后再push
                this.fetchFileList(row);
            } else {
                this.$refs.fileTable.toggleRowSelection(row)
            }
        },
        
        // 处理选择变更
        handleSelectionChange(selection) {
            // 获取新选中的项目
            const newSelection = selection.filter(item => 
                !this.selectedFiles.some(file => file.path === item.path)
            );

            // 处理新选中的项目
            newSelection.forEach(item => {
                if (item.isDirectory) {
                    // 如果是文件夹，获取其下所有文件
                    this.fetchAllFilesInDirectory(item.path);
                } else {
                    // 如果是文件，直接添加到选中列表
                    this.selectedFiles.push(item);
                }
            });

            // 处理取消选中的项目
            const deselectedItems = this.selectedFiles.filter(file => 
                !selection.some(item => item.path === file.path)
            );

            deselectedItems.forEach(item => {
                if (item.isDirectory) {
                    // 如果取消选中文件夹，移除其下所有文件
                    this.selectedFiles = this.selectedFiles.filter(file => 
                        !file.path.startsWith(item.path + '/')
                    );
                } else {
                    // 如果取消选中文件，直接从列表中移除
                    this.selectedFiles = this.selectedFiles.filter(file => 
                        file.path !== item.path
                    );
                }
            });
        },

        // 获取目录下所有文件
        fetchAllFilesInDirectory(dirPath) {
            this.$axios({
                method: "post",
                url: DMSip + '/-/bin.preData.get_path',
                data: JSON.stringify({
                    path: dirPath
                }),
            }).then(res => {
                if (res.data && res.data.code === 200 && Array.isArray(res.data.data)) {
                    // 处理返回的文件列表
                    res.data.data.forEach(item => {
                        const isDirectory = !item.includes('.');
                        const fullPath = `${dirPath}/${item}`;

                        // 只添加文件，不处理文件夹
                        if (!isDirectory) {
                            const fileInfo = {
                                name: item,
                                path: fullPath,
                                isDirectory: false,
                                selected: true
                            };
                            
                            if (!this.selectedFiles.some(f => f.path === fileInfo.path)) {
                                this.selectedFiles.push(fileInfo);
                            }
                        }
                    });
                }
            }).catch(error => {
                console.error('获取目录文件失败:', error);
                this.$message.error(`获取文件夹 ${dirPath} 下的文件失败`);
            });
        },

        // 导航到面包屑位置
        navigateToBreadcrumb(index) {
            // 获取目标路径
            const targetPath = this.breadcrumbItems[index].path
            this.currentPath = targetPath
            
            // 更新面包屑导航
            this.breadcrumbItems = this.breadcrumbItems.slice(0, index + 1)
            
            // 获取新路径的文件列表
            this.fetchFileList()
        },
        
        // 移除选中的文件
        removeSelectedFile(file) {
            // 从选中文件列表中移除
            this.selectedFiles = this.selectedFiles.filter(item => item.path !== file.path);
            
            // 如果文件在当前显示的列表中，取消其选中状态
            const tableRow = this.fileList.find(item => item.path === file.path);
            if (tableRow) {
                this.$refs.fileTable.toggleRowSelection(tableRow, false);
            }
        },
        
        // 清空选中的文件
        clearSelectedFiles() {
            this.selectedFiles = []
            this.$refs.fileTable.clearSelection()
        },
        
        // 提交数据重传
        submitRetransmission() {
            if (this.selectedFiles.length === 0) {
                this.$message.warning('请至少选择一个文件进行重传')
                return
            }
            
            // 获取当前目录
            const dirPath = this.currentPath
            
            // 获取选中文件的路径列表
            const filePaths = this.selectedFiles.map(file => file.path)
            
            this.$confirm(`确定要重传选中的 ${this.selectedFiles.length} 个文件吗？`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.retransmissionLoading = true
                
                this.$axios({
                    method: "post",
                    url: DMSip + '/-/bin.preData.data_retransmission',
                    data: JSON.stringify({
                        path: dirPath,
                        files: filePaths
                    }),
                }).then(res => {
                    if (res.data && res.data.code === 200) {
                        this.$message.success(res.data.msg || '重传成功')
                        this.closeFileManagerDialog()
                    } else {
                        this.$message.error(res.data.msg || '重传失败')
                    }
                }).catch(error => {
                    console.error('数据重传失败:', error)
                    this.$message.error('数据重传失败，请检查网络连接')
                }).finally(() => {
                    this.retransmissionLoading = false
                })
            }).catch(() => {
                this.$message.info('已取消重传')
            })
        },
        handleSizeChange(val) {
            this.pageSize = val;
            this.currentPage = 1; // 切换每页条数时回到第一页
        },
        handleCurrentChange(val) {
            this.currentPage = val;
        },
    },
    beforeUnmount() {
        // 清除页面定时器
        clearInterval(this.timer)
    },
}
</script>

<style>
.navsp {
    color: black;
    width: 85%;
    text-align: left;
    line-height: 50px;
    padding-left: 5%;
    font-weight: bold;
}

.tit {
    font-family: Source Han Sans SC, Source Han Sans SC;
    font-weight: bold;
    font-size: 26px;
    color: #FFFFFF;
    line-height: 56px;
    letter-spacing: 4px;
    font-style: normal;
    text-transform: none;
    text-align: center;
}

.btn {
    display: inline-block;
    width: 120px;
    cursor: pointer;
}

/* 数据重传列表弹窗样式 */
.file-manager-container {
    display: flex;
    flex-direction: column;
    height: 100%;
}

.station-selector {
    margin-bottom: 20px;
}

.path-navigator {
    margin-bottom: 15px;
    padding: 10px;
    background-color: #f5f7fa;
    border-radius: 4px;
}

.file-list-container {
    min-height: 350px;
    margin-bottom: 15px;
}

.selected-files-container {
    margin-top: 15px;
    padding: 10px;
    background-color: #f5f7fa;
    border-radius: 4px;
    max-height: 200px;
    overflow: hidden;
    position: relative;
}

.selected-files-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    position: sticky;
    top: 0;
    z-index: 1;
    background-color: #f5f7fa;
    padding: 5px 0;
}

.selected-title {
    font-weight: bold;
    color: #606266;
}

.selected-files-tags {
    display: flex;
    flex-wrap: wrap;
    overflow-y: auto;
    max-height: 150px;
    padding-right: 5px;
    gap: 8px;
}

.file-tag {
    margin: 0;
    word-break: break-all;
    height: auto;
    white-space: normal;
    line-height: 1.4;
    padding: 5px 10px;
    display: inline-flex;
    align-items: center;
}

.file-tag .el-tag__close {
    position: relative;
    top: 0;
    margin-left: 8px;
}
</style>
